package bTree.LeetCode;

import java.util.ArrayList;
import java.util.List;

public class N皇后 {
    List<List<String>> res = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] path = new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int i1 = 0; i1 < n; i1++) {
                path[i][i1] = '.';
            }
        }
        int row = 0;
        backtracking(path, n, row);
        return res;
    }

    private void backtracking(char[][] path, int n, int row) {
        if (row == n) {
            res.add(charToList(path));
            return;
        }
        char[] chars = path[row];
        for (int i = 0; i < n; i++) {
            chars[i] = 'Q';
            if (isValid(path, row, i, n)) {
                backtracking(path, n, row + 1);
            }
            chars[i] = '.';
        }
    }

    private boolean isValid(char[][] path, int row, int i, int n) {
        //判断同列
        for (int i1 = 0; i1 < n; i1++) {
            if (path[i1][i] == 'Q' && i1 != row) {
                return false;
            }
        }
        //右上判断
        int line = i + 1;
        for (int startRow = row - 1; startRow >= 0; startRow--) {
            if (line >= n) {
                break;
            }
            if (path[startRow][line] == 'Q') {
                return false;
            }
            line++;
        }
        //左上判断
        int line2 = i - 1;
        for (int startRow = row - 1; startRow >= 0; startRow--) {
            if (line2 < 0) {
                break;
            }
            if (path[startRow][line2] == 'Q') {
                return false;
            }
            line2--;
        }
        return true;
    }

    private List<String> charToList(char[][] path) {
        List<String> res = new ArrayList<>();
        for (char[] chars : path) {
            String s = new String();
            for (int i = 0; i < chars.length; i++) {
                s += chars[i];
            }
            res.add(s);
        }
        return res;
    }
}